<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends MY_Controller {
    
    private $model='login';
    private $table='admin';
    
	function __construct()
    {
        parent::__construct();
    }
	
	public function index()
	{
	    $this->form_validation->set_rules('username', '用户名', 'required');
	    $this->form_validation->set_rules('password', '密码', 'required');
	    $this->form_validation->set_rules('checkcode', '验证码', 'required|min_length[4]|max_length[4]');
	    //提交验证
	    if ($this->form_validation->run() == FALSE){
	        $this->load->view($this->config->item('system_manage_path').'login');
	    }else{
    	    if($this->input->post('action')=='login')
    		{
    			//接收表单数据
    			$username=$this->input->post('username');
    			$password=md5($this->input->post('password'));
    			$checkcode=$this->input->post('checkcode');
    			//判断验证码
    			$expiration = time() - 7200; // Two hour limit
    			$ids=$this->admin_model->get_field('captcha','captcha_id','captcha_time < '.$expiration);
    			$this->admin_model->del($this->table,$ids);
    			//判断验证码
    			$check=$this->admin_model->get_field('captcha','captcha_id',"word ='".$checkcode."' AND ip_address = '".$this->input->ip_address()."' AND captcha_time > ".$expiration);
    			if (count($check) > 0){
    			    //判断用户
        			$user = $this->admin_model->get_field($this->table,'id',"adminname='".$username."' AND password='".$password."'");
        			if (count($user)>0){
            			// session记录登陆者信息
            			$users = array(
            				'userid'  => $user['id'],
            				'username'  => $username,
            				'logged_in' => TRUE,
            			);
                       	$this->session->set_userdata($users);
        				//登录成功跳转到管理首页
        				$this->success('登录成功',2,$this->config->item('system_manage_path').'welcome');
        
        			// 用户名称和密码不匹配
        			}else{
        				//登录失败，重新跳转到登录页面
        				$this->error('账号或密码错误，请重新登录',2,$this->config->item('system_manage_path').'login');
        			}
    			}else{
    			    $this->error('验证码输入错误',2,$this->config->item('system_manage_path').'login');
    			}
    		}
	    }
	}
	
	
}
